Sample Scripts - Form ValidationScript #4. Simple form validationView example nowWhen you include forms on your site, for whatever reason, it would be nice to be able to check the data which has been input before the form gets posted. Here is a (relatively) simple script which checks that an e-mail address has been entered in the correct format. :- <SCRIPT LANGUAGE=JAVASCRIPT> function validEmail(email) { invalidChars = " /:,;" if (email == "") { return false }This creates a function to which the contents of the e-mail field of the form will be passed. It then creates a variable (invalidChars) which contains the five invalid characters for an email address. It also ensures that the field is not left blank. for (i=0; i<invalidChars.length; i++) { badChar = invalidChars.charAt(i) if (email.indexOf(badChar,0) !=-1) { return false } }This section cycles through the string of bad charaters and when it encounters one in the form field it saves that character in badChar, and carries on until it has checked for all bad characters. indexOf looks for the position that the bad character appears in the email address. atPos = email.indexOf("@",1) if (atPos == -1) { return false }Here the script checks for the position of the @ sign, If it doesn't find one, it returns false, that is, it says the address is wrong. if (email.indexOf("@",atpos+1) !=-1) { return false }Now it checks that there is only one @ sign, rejecting anything with more than one. fullstopPos = email.indexOf(".",atPos) if (fullstopPos == -1) { return false } if (fullstopPos+3 > email.length) { return false } return true } We now have to provide a function that tells the browser what to do when the user presses the submit button. function submitMyFrom (form) { if (!validEmail(form.emailAddr.value)) { alert ("Inavlid Email address") form.emailAddr.focus() form.emailAddr.select() return false } return true }And that's that. (PHEW !) So, let's see this script in action :- View Source |
<< BACK | - HOME - | NEXT >> |